package controllers

import (
	beego "github.com/beego/beego/v2/server/web"
	"novel/models"
	"path/filepath"
	"strings"
)

type NovelController struct {
	beego.Controller
}

// 小说发布
func (c *NovelController) Add() {
	title := c.GetString("title")
	author := c.GetString("author")
	types := c.GetString("types")
	file, header, err := c.GetFile("img")
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "请选择要上传的文件",
		}
		c.ServeJSON()
		return
	}
	defer file.Close()
	//验证文件大小
	if header.Size > 2*1024*1024 {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "文件大小不能超过2MB",
		}
		c.ServeJSON()
		return
	}
	//验证文件格式
	ext := map[string]bool{
		".jpg":  true,
		".png":  true,
		".jpeg": true,
	}
	suffix := strings.ToLower(filepath.Ext(header.Filename))
	if ext[suffix] == false {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "请选择正确的文件格式",
		}
		c.ServeJSON()
		return
	}
	path := "static/img/" + header.Filename
	c.SaveToFile("img", path)
	var novels models.Novel
	novels.Title = title
	novels.Author = author
	novels.Types = types
	novels.Img = "http://127.0.0.1:8080/" + path
	err = novels.Add()
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "上传失败",
		}
		c.ServeJSON()
	} else {
		c.Data["json"] = map[string]interface{}{
			"code": 200,
			"msg":  "上传成功",
		}
		c.ServeJSON()
	}
}
